﻿#region using namespaces

using System;
using System.Collections.Generic;
using System.Data.Linq;
using System.Linq;

#endregion

namespace RSteel.DAO
{
    public class BaseDaoContext<T> : BaseContext where T : class
    {
        public void Update(T obj, Action<T> update)
        {
            using (var dc = GetDataContext())
            {
                dc.GetTable<T>().Attach(obj);
                update(obj);
                dc.SubmitChanges();
            }
        }

        public void Update(T obj)
        {
            Update(obj, delegate { });
        }

        public void UpdateAll(List<T> items, Action<T> update)
        {
            using (var dc = GetDataContext())
            {
                Table<T> table = dc.GetTable<T>();
                foreach (T item in items)
                {
                    table.Attach(item);
                    update(item);
                }

                dc.SubmitChanges();
            }
        }

        public void Delete(T entity)
        {
            using (var dc = GetDataContext())
            {
                Table<T> table = dc.GetTable<T>();
                table.Attach(entity);
                table.DeleteOnSubmit(entity);
                dc.SubmitChanges();
            }
        }

        public void Insert(T obj)
        {
            using (var dc = GetDataContext())
            {
                dc.GetTable<T>().InsertOnSubmit(obj);
                dc.SubmitChanges();
            }
        }

        public IList<T> Execute(string query, params object[] parameters)
        {
            return Execute<T>(query, parameters);
        }

        public static IList<TResult> Execute<TResult>(string query, params object[] parameters)
        {
            using (var dc = GetDataContext())
            {
                IEnumerable<TResult> executedQuery = dc.ExecuteQuery<TResult>(query, parameters);
                return executedQuery.ToList();
            }
        }

        public IList<T> GetAllObjects()
        {
            using (var dc = GetDataContext())
            {
                return dc.GetTable<T>().ToList();
            }
        }
    }
}